package com.xnx3.wangmarket.admin.controller;

import com.xnx3.j2ee.func.AttachmentFile;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.j2ee.vo.UploadFileVO;
import com.xnx3.wangmarket.Utils.FileUtil;
import com.xnx3.wangmarket.Utils.ServerAddressUtils;
import com.xnx3.wangmarket.admin.entity.CompanyInfo;
import com.xnx3.wangmarket.admin.entity.Page;
import com.xnx3.wangmarket.admin.entity.Product;
import com.xnx3.wangmarket.admin.entity.SiteColumn;
import com.xnx3.wangmarket.admin.service.ProductManagementService;
import com.xnx3.wangmarket.admin.service.impl.ProductManagemengImpl;
import com.xnx3.wangmarket.admin.util.AliyunLog;
import com.xnx3.wangmarket.admin.vo.bean.ProductVO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xnx3.j2ee.shiro.ShiroFunc.getUserId;

@Controller
@RequestMapping("/productManagement")
public class ProductManagementController {


    @Resource
    private SqlService sqlService;

    @Resource
    private ProductManagementService productService;
    String productImg;

    @RequestMapping("/queryProductList.do")
    public String queryProductList(Model model,HttpServletRequest request){
        List<SiteColumn> site = productService.productType(getUserId());
        Product product = new Product();
        String productName = request.getParameter("productName");
        String productType = request.getParameter("productType");
        if (productName!=null && productType!=null&&!productName.isEmpty()&&!productType.isEmpty()) {
            product.setProductName(productName);
            product.setSiteColumnId(Integer.parseInt(productType));
        }
        if (productName!=null&&!productName.isEmpty()) {
            product.setProductName(productName);
        }
        if (productType!=null&&!productType.isEmpty()) {
            product.setSiteColumnId(Integer.parseInt(productType));
        }
        if (productType!=null&&!productType.isEmpty()&&productName!=null&&!productName.isEmpty()) {
            product.setSiteColumnId(Integer.parseInt(productType));
            product.setProductName(productName);
        }
        int currentPage = 1;
        int countPage = 10;
        String value = request.getParameter("page");
        if (value != null && !"".equals(value)) {
            currentPage = Integer.parseInt(value);
        }
        Page pg = productService.findPage(currentPage, countPage, product);

        Map<String,Object> map = new HashMap<>();
        map.put("type",site);
        map.put("pctList",pg);

        model.addAttribute("type", site);
        model.addAttribute("pctList", pg);
        return "site/productManagement";
    }

    //新增/编辑产品数据获取
    @RequestMapping("/eidtproductList.do")
    @ResponseBody
    public Map<String,Object> eidtproductList(HttpServletRequest request) {
        List<SiteColumn> site = productService.productType(getUserId());
        String page = request.getParameter("page");
        Product product = new Product();
        String productName = request.getParameter("productName");
        String productType = request.getParameter("type");
        if (productName!=null && productType!=null&&!productName.isEmpty()&&!productType.isEmpty()) {
            product.setProductName(productName);
            product.setSiteColumnId(Integer.parseInt(productType));
        }
        if (productName!=null&&!productName.isEmpty()) {
            product.setProductName(productName);
        }
        if (productType!=null&&!productType.isEmpty()) {
            product.setSiteColumnId(Integer.parseInt(productType));
        }
        if (productType!=null&&!productType.isEmpty()&&productName!=null&&!productName.isEmpty()) {
            product.setSiteColumnId(Integer.parseInt(productType));
            product.setProductName(productName);
        }
        int currentPage = 1;
        int countPage = 10;

        if (page != null && !"".equals(page)) {
            currentPage = Integer.parseInt(page);
        }
        Map<String,Object> map = new HashMap<>();
        Page pg = productService.findPage(currentPage, countPage, product);
        map.put("type",site);
        map.put("pctList",pg);
        return map;
    }

    //新增产品数据获取
    @RequestMapping("/productAddList.do")
    public String productAddList(Model model, HttpServletRequest request) {

        if (request.getParameter("id")!=null && !"".equals(request.getParameter("id"))) {
            String id = request.getParameter("id");
            if(Integer.parseInt(id)>0){
                Product  pct = productService.queryProduct(Integer.parseInt(id));
                model.addAttribute("pct",pct);
            }
        }
        List<SiteColumn> site = productService.productType(getUserId());
        model.addAttribute("siteType", site);

        return "site/productAdd";
    }

    //新增产品
    @RequestMapping("/productAdd.do")
    @ResponseBody
    public ProductVO productAdd(Product product, HttpServletRequest request,Model model) {

        Integer id = Integer.parseInt(request.getParameter("product_type"));
        ProductVO productVO = new ProductVO();
//        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/";
        SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = sdft.format(new Date().getTime());
        Product pct = new Product();

        if (!request.getParameter("id").equals("")) {
            Integer cid = Integer.parseInt(request.getParameter("id"));
            if (cid > 0) {
                Product prod = sqlService.findById(Product.class, cid);

                if (prod.getId() == cid) {

                    if (productImg != null&&!"".equals(productImg)) {
                        prod.setImgPath(productImg);
                    }
                    if (product.getPrice() != null) {
                        prod.setPrice(product.getPrice());
                    }
                    if (product.getProdoctDescription() != null) {
                        prod.setProdoctDescription(product.getProdoctDescription());
                    }
                    if (product.getProductName() != null) {
                        prod.setProductName(product.getProductName());
                    }
                    if (product.getAddress() != null) {
                        prod.setAddress(product.getAddress());
                    }
                    prod.setModifyTime(dateTime);
                    prod.setSiteColumnId(id);
                    prod.setUserId(getUserId());
                    productService.updateProductInfo(prod, cid, request);
//                    productService.updateProduct(cid,pct);
                    model.addAttribute("productName",product.getProductName());
                    productVO.setBaseVO(BaseVO.SUCCESS, prod.getId() > 0 ? "保存成功！" : "创建成功！");
                    productVO.setProduct(pct);
                }
            }
        } else {
            SiteColumn column = productService.pctType(id);
            if (product.getPrice() == null || product.getProductName() == null) {
                productVO.setBaseVO(BaseVO.FAILURE, "保存失败！");
                productVO.setProduct(pct);
            } else {
                if (column.getId() > 0 && id > 0) {

                    pct.setImgPath(productImg);
                    pct.setModifyTime(dateTime);
                    pct.setPrice(product.getPrice());
                    pct.setProdoctDescription(product.getProdoctDescription());
                    pct.setProductName(product.getProductName());
                    pct.setTimestamps(dateTime);
                    pct.setUserId(getUserId());
                    pct.setSiteColumnId(id);
                    pct.setAddress(product.getAddress());
                    productService.updateProductInfo(pct, getUserId(), request);
                    productVO.setBaseVO(BaseVO.SUCCESS, pct.getId() > 0 ? "保存成功！" : "创建成功！");
                    productVO.setProduct(pct);
                }
            }
        }
        productImg = "";
        return productVO;
    }

    /**
     * 删除产品信息
     ***/
    @RequestMapping("/delProduct.do")
    @ResponseBody
    public ProductVO delProduct(HttpServletRequest request) {

        ProductVO productVO = new ProductVO();
        String id = request.getParameter("id");
        if(id!=null&&!"".equals(id)){
            Product pct = new Product();
            pct.setId(Integer.parseInt(id));

            Product pcdt = sqlService.findById(Product.class,Integer.parseInt(id));
            FileUtil.deleteFile(ServerAddressUtils.tomcatPath(request)+pcdt.getImgPath());

            productService.delProduct(pct);
            productVO.setBaseVO(BaseVO.SUCCESS, Integer.parseInt(id) > 0 ? "保存成功！" : "创建成功！");
            productVO.setProduct(pct);
        }else{
            productVO.setBaseVO(BaseVO.FAILURE,"删除失败！");
        }

        return productVO;
    }

    /**
     * 上传轮播图片接口
     */
    @RequestMapping(value = "uploadProductImg${url.suffix}", method = RequestMethod.POST)
    @ResponseBody
    public UploadFileVO uploadProductImg(Model model, HttpServletRequest request) {

        UploadFileVO uploadFileVO = AttachmentFile.uploadImage("site/" + getUserId() + "/news/productImg/", request, "file", 0);
        if (uploadFileVO.getResult() == UploadFileVO.SUCCESS) {
            //上传成功，写日志
            productImg = uploadFileVO.getPath();
            AliyunLog.addActionLog(getUserId(), "内容管理上传图片成功：" + uploadFileVO.getFileName(), uploadFileVO.getPath());
        }
        return uploadFileVO;
    }

}
